// pages/shops/list/list.js
import regeneratorRuntime from '../../../utils/regeneratorRuntime.js'

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    cates: [],
    contHeight: null,
    current_page: 0,
    last_page: 0,
    cate_id: 0,
    actEndTimeList: [],
    countDownList: [],
    LoadingTime: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    this.setData({
      contHeight: `height:${wx.getSystemInfoSync().windowHeight - 44}px`
    })
    this.getIndex()
  },

  onMore() {
    // 检查是否有下一页
    if (this.data.current_page < this.data.last_page) {
      this.getIndex();
    }
  },

  getIndex() {
    this.setData({ list: [] })
    let page = this.data.current_page + 1
    let cate_id = this.data.cate_id
    let endTimeList = []
    app.shop.getShopIndex(page, cate_id)
      .then(res => {
        console.log(res)
        res.data.forEach(o => {
          endTimeList.push({
            id: o.id,
            end_time: (o.time_status == 1 ? o.active_end_timestamp : o.active_start_timestamp ) * 1000
          })
        })
        let list = this.data.list;
        if (page == 1) {
          list = [];
        }
        if (res.data.length > 0) {
          res.data.forEach((item)=> {
            list.push(item);
          });
        } else { list = [] }
        this.setData({
          last_page: res.last_page,
          current_page: res.current_page,
          cates: res.cates.length > 0 ? res.cates : this.data.cates,
          list,
          actEndTimeList: endTimeList
        })
        // 执行倒计时函数
        this.countDown()
      })
      .catch((error) => {
        // app.toast(error)
      })
  },

  timeFormat(param) {//小于10的格式化函数
    return param < 10 ? '0' + param : param;
  },

  countDown() {//倒计时函数
    // 获取当前时间，同时得到活动结束时间数组
    let newTime = new Date().getTime();
    let endTimeList = this.data.actEndTimeList;
    let countDownArr = [];

    // 对结束时间进行处理渲染到页面
    endTimeList.forEach(o => {
      let endTime = o.end_time;
      let obj = null;
      // 如果活动未结束，对时间进行处理
      if (endTime - newTime > 0) {
        let time = (endTime - newTime) / 1000;
        // 获取天、时、分、秒
        let day = parseInt(time / (60 * 60 * 24));
        let hou = parseInt(time % (60 * 60 * 24) / 3600);
        let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
        let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
        obj = {
          day: this.timeFormat(day),
          hou: this.timeFormat(hou),
          min: this.timeFormat(min),
          sec: this.timeFormat(sec)
        }
      } else {//活动已结束，全部设置为'00'
        obj = {
          day: '00',
          hou: '00',
          min: '00',
          sec: '00'
        }
      }
      countDownArr[o.id] = obj;
    });
    clearInterval(this.data.LoadingTime);
    // 渲染，然后每隔一秒执行一次倒计时函数
    var that = this;
    let LoadingTime = setInterval(function () {
      that.countDown();
    }, 1000);
    this.setData({
      countDownList: countDownArr, LoadingTime: LoadingTime
    })
  },

  onDetails({detail}) {
    wx.navigateTo({
      url: `/pages/shops/shop/shop_details?id=${detail}`
    })
  },

  async onSnapUp({detail}) {
    try {
      const { id } = await app.shop.getOrderID(detail)
      wx.navigateTo({
        url: `/pages/shops/order/orde_details?id=${id}`,
      })
    } catch(err) {
      console.log(err)
      app.toast(err)
    }
  },

  onChange({ detail: { index: curr }}){
    if (curr === 0) {
      this.setData({
        current_page: 0,
        active: 0,
        cate_id: 0
      });
      this.getIndex();
    }
    this.data.cates.forEach((item, index) => {
      if (index === curr - 1) {
        this.setData({
          current_page: 0,
          active: curr,
          cate_id: item.id
        });
        this.getIndex();
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearInterval(this.data.LoadingTime);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(this.data.LoadingTime);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})